package edu.nus.mtech.sem1.ca.utils;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JOptionPane;

/**
 * A glorified text box control with validation and auto-population of current date
 * 
 * Care has been taken while constructing this class.  After all, these are the only dates a programmer gets.
 *
 */
public class DateInputControl extends javax.swing.JTextField {
	
	private Date mDate;
	public DateInputControl(){
		super();
		addFocusListener(new FocusListener() {
			@Override
			public void focusLost(FocusEvent focusEvent) {
				validateInput();		
			}
			
			@Override
			public void focusGained(FocusEvent focusEvent) {
				showToolTip();
				
			}
		});
		mDate=null;
		
		addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent event){
				if (event.getClickCount()>=2){
					populateCurrentDate();
				}
			}

		
		});
	}
	
	
	public Date getDate(){
		validateInput();
		return this.mDate;
	}
	
	private void showToolTip() {

		this.setText("Double click for today");
	}
	
	private void populateCurrentDate() {
		this.setText(TelephonyUtils.getStringFromDate(Calendar.getInstance().getTime()));
	}
	
	public void validateInput(){
		String[] l_arr= super.getText().split("/");
		if(super.getText().trim().length()>0){
			if(l_arr.length<3 ){
				this.setText("");
				this.requestFocus();
				JOptionPane.showMessageDialog(null, "Date format must be dd/mm/yyyy.", "Error", JOptionPane.ERROR_MESSAGE);
			}
			else if(l_arr[0].length()<2 || l_arr[1].length()<2 || l_arr[2].length()<4){
				this.setText("");
				this.requestFocus();
				JOptionPane.showMessageDialog(null, "Date format must be dd/mm/yyyy.", "Error", JOptionPane.ERROR_MESSAGE);
			}
			else{
				
				DateFormat l_df=new SimpleDateFormat("dd/MM/yyyy");
				if(this.getText().split(":").length>2){
					l_df= new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); 
				}
				try {					
					mDate= l_df.parse( this.getText());
					
				} catch (ParseException e) {
					JOptionPane.showMessageDialog(null, "Invalid date!", "Error", JOptionPane.ERROR_MESSAGE);
					this.setText("");
					this.requestFocus();
					// TODO: handle exception
				}catch (Exception e2){
					Logger.log(e2.getStackTrace());
				}
				
			}
		}
	}
}
